package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.controller.excel.ReturnExcel;
import com.example.springboot.entity.Return;
import com.example.springboot.service.IBorrowService;
import com.example.springboot.utils.ExcelImportUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/return")
public class ReturnController {

    @Resource
    private IBorrowService borrowService;

    /**
     * 批量删除
     * @param ids ids
     * @return Result
     */
    @DeleteMapping("/deleteBatch")
    public Result delete(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            borrowService.deleteReturById(id);
        }
        return Result.success();
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        List<ReturnExcel> returnList = ExcelImportUtil.importExcel(file, ReturnExcel.class);
        for (ReturnExcel returnExcel : returnList) {
            // 定义只提取日期部分的格式化器
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/M/d");
            // 进行转换
            String returnDate = returnExcel.getReturnDate();
            String createtime = returnExcel.getCreatetime();
            String updatetime = returnExcel.getUpdatetime();
            String realDate = returnExcel.getRealDate();

            LocalDate returnTime = null;
            LocalDate createTime = null;
            LocalDate updateTime = null;
            LocalDate realDateTime = null;
            if (returnDate != null){
                returnTime = LocalDate.parse(returnDate.substring(0, returnDate.indexOf(' ')), dateFormatter);
            }
            if (createtime != null){
                createTime = LocalDate.parse(createtime.substring(0, createtime.indexOf(' ')), dateFormatter);
            }
            if (updatetime != null){
                updateTime = LocalDate.parse(updatetime.substring(0, updatetime.indexOf(' ')), dateFormatter);
            }
            if (realDate != null){
                realDateTime = LocalDate.parse(realDate.substring(0, realDate.indexOf(' ')), dateFormatter);
            }
            Return re = new Return();
            BeanUtils.copyProperties(returnExcel, re);
            re.setReturnDate(returnTime);
            re.setCreatetime(createTime);
            re.setUpdatetime(updateTime);
            re.setRealDate(realDateTime);
            borrowService.saveUploadRe(re);
        }
        return Result.success();
    }
}
